#!/usr/bin/env python
"""
A quick script to install into your `Application Support/BBEdit/Scripts` folder.
This runs PyFlakes (requires PyFlakes to be installed at `/usr/local/bin` -
try ``/usr/bin/easy_install-2.6 pyflakes==0.4.0``) and reformats the results
so that they show up in BBEdit's search results / error / warnings window. Then
the errors can be stepped through one at a time.

I've bound this to control-shift-V. You must save your Python file first before
running the check.
"""
from __future__ import print_function
import os
import re
import sys
from subprocess import Popen, PIPE

PYFLAKES = "/usr/local/bin/pyflakes"

def main():
    try:
        doc_file = os.environ['BB_DOC_PATH']
    except KeyError:
        print('BB_DOC_PATH not found, maybe your file is not yet saved.', file=sys.stderr)
        sys.exit(1)

    Out, Err = Popen([PYFLAKES, doc_file], stdout=PIPE, stderr=PIPE).communicate()
    if Out:
        Output = Out
    else:
        Output = Err

    if not Output:
        sys.exit(0)

    LINE_FORMAT = re.compile('(?P<path>[^:]+):(?P<line>\d+):\s(?P<message>.*$)')
    for line in Output.splitlines():
        m_line = LINE_FORMAT.match(line)
        if  m_line:
            groups = m_line.groupdict()
            print('''  File "{path}", line {line},'''.format(**groups), file=sys.stderr)
            print(groups['message'], file=sys.stderr)

    sys.exit(1)

if __name__ == '__main__':
    main()
